#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    bool dfs(string& str, int pos, int sum, int target) {
        if (pos == str.size()) {
            return sum == target;
        }
        int t = 0;
        for (int i = pos; i < str.size(); i++) {
            t = t * 10 + str[i] - '0';
            if (t + sum > target) {
                return false;
            }
            if (dfs(str, i + 1, t + sum, target)) {
                return true;
            }
        }
        return false;
    }
    int punishmentNumber(int n) {
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            string str = to_string(i * i);
            if (dfs(str, 0, 0, i)) {
                ans += i * i;
            }
        }
        return ans;
    }
};


